package models

import (
	"fmt"
	"github.com/astaxie/beego/orm"
	"time"
)

/**
 *  @Title  测试用例
 *  @author liqi 2018/12/12 13:45
 *  @Description 
 */

type YyUser struct {
	Id            int       `orm="auto;pk"`
	Sex           int       `form:"sex"`
	Username      string    `form:"username"`
	Nickname      string    `form:"nickname"`
	Created_at    time.Time `form:"created_at"`
	Register_type int       `form:"register_type"`
}

// @Title 注册model
// @author  liqi 2018/12/12 13:46
// @Description
func init() {
	orm.RegisterModel(new(YyUser))
}

// 查询所有
func QueryUserAll() []YyUser {
	o := orm.NewOrm()
	qs := o.QueryTable("yy_user")
	var users []YyUser
	count, err := qs.Filter("id__lte", 10).OrderBy("-id").All(&users)
	if err == nil {
		fmt.Printf("count", count)
	}
	return users
}

// 查询(id)
func QueryUserById(id int) (YyUser, bool) {
	o := orm.NewOrm()
	user := YyUser{Id: id}
	err := o.Read(&user)
	if err == orm.ErrNoRows {
		fmt.Println("查询不到~")
		return user, false
	} else if err == orm.ErrMissPK {
		fmt.Println("找不到主键~")
		return user, false
	} else {
		return user, true
	}
}

// 创建
func CreateUser(form YyUser) (int64, bool) {
	o := orm.NewOrm()
	user := new(YyUser)
	user.Sex = form.Sex
	user.Username = form.Username
	user.Nickname = form.Nickname
	user.Created_at = form.Created_at
	// 直接将传来的参数添加也可以
	//	id, err := o.Insert(&form)
	id, err := o.Insert(&form)
	if err == nil {
		fmt.Println("创建成功~")
		return id, true
	} else {
		fmt.Println("创建失败~")
		return id, false
	}
}

// 更新
func UpdateUserById(id int, form YyUser) bool {
	o := orm.NewOrm()
	user := YyUser{Id: id}
	if o.Read(&user) == nil {
		user.Sex = form.Sex
		user.Username = form.Username
		user.Nickname = form.Nickname
		user.Created_at = form.Created_at
		if num, err := o.Update(&user); err == nil {
			if num > 0 {
				return true
			}
		}
	}
	return false
}

// 删除(id)
func DeleteUserById(id int) bool {
	o := orm.NewOrm()
	user := YyUser{Id: id}
	num, err := o.Delete(&user)
	if err == nil {
		if num > 0 {
			return true
		}
	}
	return false
}
